import Vue from 'vue'
import axios from 'axios'
import router from '@/router'
import qs from 'qs'
import merge from 'lodash/merge'
import { clearLoginInfo } from '@/utils'
import {Loading, Message} from 'element-ui'

let loadingControl = null;
let threadPoor = []

const httpN = axios.create({
  timeout: 1000 * 30,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
})

httpN.interceptors.request.use(config => {
  let timeCounter = setTimeout(() => {
    if(!loadingControl) loadingControl = Loading.service({fullscreen: true,background: 'rgba(0, 0, 0, 0.7)',text: '加载中...'});
  },200)
  threadPoor.push(timeCounter);

  config.headers['token'] = Vue.cookie.get('token')
  return config
}, error => {
  Message.error(error);
  return
})

httpN.interceptors.response.use(response => {
  let currentThread = threadPoor.shift();
  clearTimeout(currentThread)
  if(threadPoor.length === 0 && loadingControl) {
    loadingControl.close();
    loadingControl = null;
  }

  let responseData = response.data;
  if(!responseData) {
    Message.error('响应数据为空')
    return false
  }
  if(response.config.responseType === 'blob')  return responseData;
  if(responseData.code === 401) {
    clearLoginInfo()
    router.push({ name: 'login',query: {redirect: window.location.href}})
  }else if(responseData.code === 501) {
    Message.error(responseData.msg)
    return responseData.msg;
  }else if(responseData.code !== 0) {
    Message.error(responseData.msg)
    return false;
  }else if(responseData.code === 0) {
    return responseData.data ? responseData.data: true
  }
}, error => {
  let currentThread = threadPoor.shift();
  clearTimeout(currentThread)
  if(threadPoor.length === 0 && loadingControl) {
    loadingControl.close();
    loadingControl = null;
  }
  Message.error(error);
  return
})

/**
 * 数据存放在query的post
 */
httpN.postQ = (url, param, needAborn = true) => {
  return httpN({
    url: adornUrl(url),
    method: 'post',
    params: adornParams(param, needAborn)
  })
}

/**
 * 数据存放在body的post
 */
httpN.postB = (url, param, needAborn = true) => {
  return httpN({
    url: adornUrl(url),
    method: 'post',
    data: adornData(param, needAborn)
  })
}

httpN.get = (url, params = {}, type = 'json') => {
  return httpN({
    url: adornUrl(url),
    method: 'get',
    params: params,
    responseType: type
  })
}

httpN.upload = (url, file, type = 'json') => {
  let res = axios.create({
    timeout: 1000 * 30,
    withCredentials: true,
    headers: {
      'Content-Type':'multipart/form-data"',
      'token': Vue.cookie.get('token')
    },
    responseType: type
  })
  return res({
    url: adornUrl(url),
    method: 'post',
    data: file
  })
}

httpN.uploadNew = (url, file, type = 'json') => {
  return httpN({
    url: adornUrl(url),
    method: 'post',
    headers: {
      'Content-Type':'multipart/form-data"',
    },
    data: file
  })
}


function adornUrl (actionName) {
  return (process.env.NODE_ENV !== 'production' && process.env.OPEN_PROXY ? '/proxyApi/' : window.SITE_CONFIG.baseUrl) + actionName
}

function adornParams (params = {}, openDefultParams = true) {
  var defaults = {
    't': new Date().getTime()
  }
  return openDefultParams ? merge(defaults, params) : params
}


function adornData (data = {}, openDefultdata = true, contentType = 'json') {
  var defaults = {
    't': new Date().getTime()
  }
  data = openDefultdata ? merge(defaults, data) : data
  return contentType === 'json' ? JSON.stringify(data) : qs.stringify(data)
}

export default httpN
